/*
 * mouse_handler.cpp
 *
 *  Created on: 20/01/2009
 *      Author: smaxll
 */


#include "mouse_handler.hpp"
#include "board.hpp"
#include "game.hpp"
#include "SDL.h"
#include "SDL_opengl.h"

std::pair<unsigned int, unsigned int> mouse_handler::lastDownPos;

void mouse_handler::mouse_down(SDL_Event* event){
    /// save the position where the mouse is down
//    lastDownPos.first = event->button.x;
//    lastDownPos.second = event->button.y;

    if( !game_controller::is_started() ){
        /// game not yet started
//        return;
    }

    /** Get the world coordinates according to the windows screen coordinates **/
    double objX, objY, objZ;
    double modelview[16], projection[16];
    int viewport[4];
    float z;
    //get the projection matrix
    glGetDoublev( GL_PROJECTION_MATRIX, projection );
    //get the modelview matrix
    glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
    //get the viewport
    glGetIntegerv( GL_VIEWPORT, viewport );

    //Read the window z co-ordinate
    //(the z value on that point in unit cube)
    glReadPixels( event->button.x, viewport[3]-event->button.y, 1, 1,
         GL_DEPTH_COMPONENT, GL_FLOAT, &z );

    //Unproject the window co-ordinates to
    //find the world co-ordinates.
    gluUnProject( event->button.x, viewport[3]-event->button.y, z, modelview,
        projection, viewport, &objX, &objY, &objZ );

    /// Check if the mouse is inside the board
    if( !board::is_inside_board(objX, objY) ){
        /// mouse are not positioned within the board
        //TODO game menu
        return;
    }

//    std::cout << objX << " " << objY << " " << objZ << std::endl;
    board::set_chess_piece(objX, objY);

}
